package cn.edu.swu.mhans.common.player;

import cn.edu.swu.mhans.common.util.ApplicationContextProvider;
import cn.edu.swu.mhans.common.util.UserWebSocketSessionUtil;
import cn.edu.swu.mhans.user.model.SystemUser;
import cn.edu.swu.mhans.user.service.UserService;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;

import javax.websocket.Session;
import java.io.IOException;

/**
 * @author ZhanJingbo
 * @version 1.0.0
 * Created on 2018/5/1
 */

public class WebSocketHumanNegotiationPlayer extends AbstractNegotiationHumanPlayer {


    private String roomId;

    public WebSocketHumanNegotiationPlayer(SystemUser user, String roomId) {
        this.setUser(user);
        this.roomId = roomId;
    }

    /**
     * 处理传输来的数据
     *
     * @param negotiationCommand 待处理的数据
     */
    @Override
    public void handleNegotiationCommand(NegotiationCommand negotiationCommand) {
        try {
            ObjectMapper objectMapper = new ObjectMapper();
            String negotiationCommandJsonString = objectMapper.writeValueAsString(negotiationCommand);
            getUserWebSocketSession().getBasicRemote().sendText(negotiationCommandJsonString);
        } catch (JsonProcessingException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    public Session getUserWebSocketSession() {
        UserService userService = ApplicationContextProvider.getBean(UserService.class);
        String sessionKey = UserWebSocketSessionUtil.getUserWebSocketSessionKey(roomId, Long.parseLong(getNegotiationPlayerId()));
        return userService.getUserWebSocketSession(sessionKey);
    }


}
